package com.material.vtool.controller;

import com.google.common.collect.Maps;
import com.material.vtool.entity.BMaterialTypeInfoEntity;
import com.material.vtool.entity.BTeamMaterialEntity;
import com.material.vtool.entity.BTeamMaterialTypeEntity;
import com.material.vtool.entity.combinedEntity.*;
import com.material.vtool.entity.reqEntity.*;
import com.material.vtool.entity.respEntity.RespData;
import com.material.vtool.entity.respEntity.ReturnCode;
import com.material.vtool.service.*;
import com.material.vtool.utils.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 素材
 */
@RestController
public class MaterialInfoController {
    @Autowired
    private MaterialInfoService materialInfoService;

    @Autowired
    private MaterialTypeInfoService materialTypeInfoService;

    @Autowired
    private TeamMaterialService teamMaterialService;

    @Autowired
    private TeamMaterialTypeService teamMaterialTypeService;

    @Autowired
    private UserMaterialTypeService userMaterialTypeService;

    /**
     * 获取推荐文章(按时间倒序)
     * 只显示当前用户订阅频道中的推荐素材
     * @param recommendArticleReqBean 推荐文章请求实体
     * @return
     */
    @PostMapping(value = "/getRecommendArticleByTime", produces = "application/json;charset=UTF-8")
    public RespData getRecommendArticleByTime(@RequestHeader("userId") String userId,
                                              @RequestHeader("miniCode") String miniCode,
                                              @RequestBody RecommendArticleReqBean recommendArticleReqBean) {
        if (recommendArticleReqBean == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Integer pageNum = recommendArticleReqBean.getPageNum();
        Integer pageSize = recommendArticleReqBean.getPageSize();

        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = Integer.valueOf(1);
        }

        if (pageSize == null || pageNum.intValue() <= 0) {
            pageSize = Integer.valueOf(10);
        }

        // 获取用户的频道 ID 列表
        List<Integer> userMaterialTypeIdList = userMaterialTypeService.getUserMaterialTypeIdList(Integer.valueOf(userId), miniCode);
        // 获取 10 篇推荐文章（按创建时间倒序）
        List<CombinedRecommendArticleEntity> list = materialInfoService.getRecommendArticleByTime(pageNum, pageSize, userMaterialTypeIdList);
        if (CollectionUtils.isNotEmpty(list)) {
            for (CombinedRecommendArticleEntity entity : list) {
                // 获取文章的类型
                if (entity != null && entity.getMaterialTypeId() != null) {
                    // 查看上级类型
                    int parentTypeId = materialTypeInfoService.getMaterialParentTypeId(entity.getMaterialTypeId()).intValue();
                    // 如果存在上级，则使用上级类型ID
                    CombinedArticleTypeIntoEntity combinedArticleTypeIntoEntity = materialTypeInfoService.getMaterialTypeById(parentTypeId > 0 ? parentTypeId : entity.getMaterialTypeId());
                    entity.setMaterialTypeName(combinedArticleTypeIntoEntity.getMaterialTypeName());
                    entity.setMaterialTypeLogo(combinedArticleTypeIntoEntity.getMaterialTypeLogo());
                }
            }
        }

        int totalRecord = 0;// 总记录数
        int totalPage = 0;// 总页数
        totalRecord = materialInfoService.getRecommendArticleByTimeTotal(userMaterialTypeIdList);
        totalPage = totalRecord % pageSize.intValue() == 0 ? totalRecord / pageSize.intValue() : (totalRecord / pageSize.intValue()) + 1;
        PageResult pageResult = new PageResult(Integer.valueOf(totalRecord), pageSize, pageNum, Integer.valueOf(totalPage));

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("pageResult", pageResult);
        resultMap.put("recommendArticleList", list);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 获取推荐文章(点击右侧[换]按钮后，随机获取文章)
     * @return
     */
    @GetMapping(value = "/getRecommendArticle", produces = "application/json;charset=UTF-8")
    public RespData getRecommendArticle(@RequestHeader("userId") String userId, @RequestHeader("miniCode") String miniCode) {
        // 获取用户的频道 ID 列表
        List<Integer> userMaterialTypeIdList = userMaterialTypeService.getUserMaterialTypeIdList(Integer.valueOf(userId), miniCode);

        // 随机获取 10 篇推荐文章
        List<CombinedRecommendArticleEntity> list = materialInfoService.getRecommendArticle(userMaterialTypeIdList);
        if (CollectionUtils.isNotEmpty(list)) {
            for (CombinedRecommendArticleEntity entity : list) {
                // 获取文章的类型
                if (entity != null && entity.getMaterialTypeId() != null) {
                    // 查看上级类型
                    int parentTypeId = materialTypeInfoService.getMaterialParentTypeId(entity.getMaterialTypeId()).intValue();
                    // 如果存在上级，则使用上级类型ID
                    CombinedArticleTypeIntoEntity combinedArticleTypeIntoEntity = materialTypeInfoService.getMaterialTypeById(parentTypeId > 0 ? parentTypeId : entity.getMaterialTypeId());
                    entity.setMaterialTypeName(combinedArticleTypeIntoEntity.getMaterialTypeName());
                    entity.setMaterialTypeLogo(combinedArticleTypeIntoEntity.getMaterialTypeLogo());
                }
            }
        }
        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("recommendArticleList", list);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 根据素材类型获取文章
     * @param commonArticleReqBean 请求实体
     * @return
     */
    @PostMapping(value = "/getArticleByMaterialTypeId", produces = "application/json;charset=UTF-8")
    public RespData getArticleByMaterialTypeId(@RequestBody CommonArticleReqBean commonArticleReqBean) {
        if (commonArticleReqBean == null || commonArticleReqBean.getMaterialTypeId() == null || commonArticleReqBean.getMaterialTypeId().intValue() <= 0) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Integer materialTypeId = commonArticleReqBean.getMaterialTypeId();

        Integer pageNum = commonArticleReqBean.getPageNum();
        Integer pageSize = commonArticleReqBean.getPageSize();

        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = Integer.valueOf(1);
        }

        if (pageSize == null || pageNum.intValue() <= 0) {
            pageSize = Integer.valueOf(10);
        }

        List<CombinedCommonArticleEntity> list = materialInfoService.getArticleByMaterialTypeId(pageNum, pageSize, materialTypeId);
        if (CollectionUtils.isNotEmpty(list)) {
            // 查看上级类型
            int parentTypeId = materialTypeInfoService.getMaterialParentTypeId(materialTypeId).intValue();
            // 如果存在上级，则使用上级类型ID
            CombinedArticleTypeIntoEntity combinedArticleTypeIntoEntity = materialTypeInfoService.getMaterialTypeById(parentTypeId > 0 ? parentTypeId : materialTypeId);

            for (CombinedCommonArticleEntity entity : list) {
                // 获取文章的类型
                if (entity != null) {
                    entity.setMaterialTypeName(combinedArticleTypeIntoEntity.getMaterialTypeName());
                    entity.setMaterialTypeLogo(combinedArticleTypeIntoEntity.getMaterialTypeLogo());
                }
            }
        }

        int totalRecord = 0;// 总记录数
        int totalPage = 0;// 总页数
        totalRecord = materialInfoService.getArticleByMaterialTypeIdTotal(materialTypeId);
        totalPage = totalRecord % pageSize.intValue() == 0 ? totalRecord / pageSize.intValue() : (totalRecord / pageSize.intValue()) + 1;
        PageResult pageResult = new PageResult(Integer.valueOf(totalRecord), pageSize, pageNum, Integer.valueOf(totalPage));

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("pageResult", pageResult);
        resultMap.put("commonArticleList", list);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 文章收藏：收藏到用户的某个团队，如果用户有多个团队，选择一个
     * @param userId 用户ID
     * @param materialCollectBean 请求实体类
     * @return
     */
    @PostMapping(value = "/materialCollect", produces = "application/json;charset=UTF-8")
    @Transactional
    public RespData materialCollect(@RequestHeader("userId") String userId, @RequestBody MaterialCollectBean materialCollectBean) {
        if (materialCollectBean == null || materialCollectBean.getMaterialId() == null || materialCollectBean.getTeamId() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }

        Integer currentUserId = Integer.valueOf(userId);
        Integer materialId = materialCollectBean.getMaterialId();
        Integer teamId = materialCollectBean.getTeamId();

        // 如果用户收藏过该文章到该团队，直接返回
        BTeamMaterialEntity entity = teamMaterialService.getTeamMemberMaterial(currentUserId, materialId, teamId);
        if (entity != null) {
            if (entity.getStatus() != null && entity.getStatus().intValue() == 1) {
                RespData respData = new RespData();
                respData.setCode(ReturnCode.TEAM_MEMBER_MATERIAL_EXISTS);
                respData.setMsg("用户在该团队已经收藏过此素材");
                return respData;
            } else if (entity.getStatus() != null && entity.getStatus().intValue() == 0) {
                // 更新状态
                teamMaterialService.updateTeamMemberMaterialActive(currentUserId, materialId, teamId);
            }
        } else {
            // 根据文章 ID 获取文章类别名称
            BMaterialTypeInfoEntity bMaterialTypeInfoEntity = materialInfoService.getMaterialTypeByMaterialId(materialId);

            if (bMaterialTypeInfoEntity != null) {
                // 查看团队标签是否存在。如果不存在，则新增
                boolean isExist = teamMaterialTypeService.isExist(bMaterialTypeInfoEntity.getId(), teamId);
                if (!isExist) {
                    BTeamMaterialTypeEntity bTeamMaterialTypeEntity = new BTeamMaterialTypeEntity();
                    bTeamMaterialTypeEntity.setTeamId(teamId);
                    bTeamMaterialTypeEntity.setLabelTypeId(bMaterialTypeInfoEntity.getId());
                    bTeamMaterialTypeEntity.setLabelTypeName(bMaterialTypeInfoEntity.getMaterialTypeName());
                    bTeamMaterialTypeEntity.setCreateTime(DateUtil.getCurDate());
                    teamMaterialTypeService.save(bTeamMaterialTypeEntity);
                }

                // 新增团队文章
                BTeamMaterialEntity bTeamMaterialEntity = new BTeamMaterialEntity();
                bTeamMaterialEntity.setUserId(currentUserId);
                bTeamMaterialEntity.setTeamId(teamId);
                bTeamMaterialEntity.setMaterialId(materialId);
                bTeamMaterialEntity.setMaterialTypeId(bMaterialTypeInfoEntity.getId());
                bTeamMaterialEntity.setCreateTime(DateUtil.getCurDate());
                teamMaterialService.save(bTeamMaterialEntity);

                // 异步任务：用户收藏 + 文章收藏
                materialInfoService.AsyncTaskSaveMaterialCollectInfo(currentUserId, materialId);
            }
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 获取小程序的热门搜索
     * @param miniCode 小程序标识
     * @return
     */
    @GetMapping(value = "/hotSearch", produces = "application/json;charset=UTF-8")
    public RespData hotSearch(@RequestHeader("miniCode") String miniCode) {
        List<HotSearch> hotSearchEntityList = materialInfoService.getHotSearch(miniCode);
        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("hotSearch", hotSearchEntityList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 搜索文章
     * @param miniCode 小程序标识
     * @param searchMaterialReqBean 搜索文章请求实体
     * @return
     */
    @PostMapping(value = "/searchMaterialByKey", produces = "application/json;charset=UTF-8")
    public RespData searchMaterialByKey(@RequestHeader("miniCode") String miniCode, @RequestBody SearchMaterialReqBean searchMaterialReqBean) {
        if (searchMaterialReqBean == null || StringUtils.isBlank(searchMaterialReqBean.getKey())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }

        String key = searchMaterialReqBean.getKey();

        Integer pageNum = searchMaterialReqBean.getPageNum();
        Integer pageSize = searchMaterialReqBean.getPageSize();

        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = Integer.valueOf(1);
        }

        if (pageSize == null || pageNum.intValue() <= 0) {
            pageSize = Integer.valueOf(10);
        }

        List<CombinedCommonArticleEntity> searchMaterialList = materialInfoService.searchMaterialByKey(pageNum, pageSize, miniCode, key);
        if (CollectionUtils.isNotEmpty(searchMaterialList)) {
            for (CombinedCommonArticleEntity entity : searchMaterialList) {
                // 获取文章的类型
                if (entity != null && entity.getMaterialTypeId() != null) {
                    // 查看上级类型
                    int parentTypeId = materialTypeInfoService.getMaterialParentTypeId(entity.getMaterialTypeId()).intValue();
                    // 如果存在上级，则使用上级类型ID
                    CombinedArticleTypeIntoEntity combinedArticleTypeIntoEntity = materialTypeInfoService.getMaterialTypeById(parentTypeId > 0 ? parentTypeId : entity.getMaterialTypeId());
                    entity.setMaterialTypeName(combinedArticleTypeIntoEntity.getMaterialTypeName());
                    entity.setMaterialTypeLogo(combinedArticleTypeIntoEntity.getMaterialTypeLogo());
                }
            }
        }

        int totalRecord = 0;// 总记录数
        int totalPage = 0;// 总页数
        totalRecord = materialInfoService.searchMaterialByKeyTotal(miniCode, key);
        totalPage = totalRecord % pageSize.intValue() == 0 ? totalRecord / pageSize.intValue() : (totalRecord / pageSize.intValue()) + 1;
        PageResult pageResult = new PageResult(Integer.valueOf(totalRecord), pageSize, pageNum, Integer.valueOf(totalPage));

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("pageResult", pageResult);
        resultMap.put("searchMaterialList", searchMaterialList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 查看素材分享链接
     * @param materialShareLinkReqBean 请求实体
     * @return
     */
    @PostMapping(value = "/materialShareLink", produces = "application/json;charset=UTF-8")
    public RespData materialShareLink(@RequestBody MaterialShareLinkReqBean materialShareLinkReqBean) {
        if (materialShareLinkReqBean == null || materialShareLinkReqBean.getMaterialId() == null || materialShareLinkReqBean.getMaterialId().intValue() <= 0) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }

        CombinedCommonArticleEntity entity = materialInfoService.getMaterialInfoById(materialShareLinkReqBean.getMaterialId());
        // 获取文章的类型
        if (entity != null && entity.getMaterialTypeId() != null) {
            // 查看上级类型
            int parentTypeId = materialTypeInfoService.getMaterialParentTypeId(entity.getMaterialTypeId()).intValue();
            // 如果存在上级，则使用上级类型ID
            CombinedArticleTypeIntoEntity combinedArticleTypeIntoEntity = materialTypeInfoService.getMaterialTypeById(parentTypeId > 0 ? parentTypeId : entity.getMaterialTypeId());
            entity.setMaterialTypeName(combinedArticleTypeIntoEntity.getMaterialTypeName());
            entity.setMaterialTypeLogo(combinedArticleTypeIntoEntity.getMaterialTypeLogo());
        }

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("materialInfo", entity);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }
}
